package dao

import (
	"app/internal/channel"
	"app/internal/store/conf"
	"app/util"
	"app/util/nosql"
	"app/util/orm"
)

type Dao struct {
	db             *orm.Database
	cf             *conf.AppConf
	licensechannel *nosql.RedisContainer
	heartchannel   *nosql.RedisContainer
	messagechannel *nosql.RedisContainer
}

func New(conf *conf.AppConf) (dao *Dao) {

	var err error
	dao = &Dao{
		db: orm.NewORM(),
		cf: conf,
	}

	dao.licensechannel, err = nosql.NewChannel(dao.cf.Redis.Network,
		dao.cf.Redis.GetRedisAddr(),
		dao.cf.Redis.Password,
		channel.LicenseChannelIndex, dao.cf.Redis.Consize)
	if err != nil {
		util.Error("open licensechannel faild")
		return nil
	}

	dao.heartchannel, err = nosql.NewChannel(dao.cf.Redis.Network,
		dao.cf.Redis.GetRedisAddr(),
		dao.cf.Redis.Password,
		channel.HeartChannelIndex, dao.cf.Redis.Consize)
	if err != nil {
		util.Error("open heartchannel faild")
		return nil
	}

	dao.messagechannel, err = nosql.NewChannel(dao.cf.Redis.Network,
		dao.cf.Redis.GetRedisAddr(),
		dao.cf.Redis.Password,
		channel.MessageChannelIndex, dao.cf.Redis.Consize)
	if err != nil {
		util.Error("open licensechannel faild")
		return nil
	}

	if err := OpenDB(dao, conf); err != nil {
		return nil
	}

	if err := CheckTable(dao); err != nil {
		return nil
	}

	dao.ClearCacheLicense()

	if err := SyncLicenseRecords(dao); err != nil {
		util.Error("SyncLicenseRecords table %s", err)
		return nil
	}

	util.Info("Rdb size %d\n", dao.GetLicenseSize())

	return
}

func (d *Dao) Close() {
	defer d.db.Close()
	d.messagechannel.Close()
	d.licensechannel.Close()
}
